<template>
  <div class="pages salePrice">
    <div class="pageLevel">
      <!-- 头部 -->
      <div class="tableSearch">
        <el-form
          label-width="100px"
          class="demo-ruleForm"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
        >
          <el-row>
            <el-form-item label="企业客户：" prop="supplierName" label-width="150px">
              <el-input v-model="ruleForm.supplierName" disabled size="small"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="销售价格协议名称：" prop="saleName" label-width="150px">
              <el-input
                :disabled="disabledName"
                maxlength="50"
                v-model="ruleForm.saleName"
                size="small"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="协议起止时间：" prop="agreementTime" label-width="150px">
              <el-date-picker
                size="small"
                :disabled="disableds"
                v-model="ruleForm.agreementTime"
                type="daterange"
                range-separator="至"
                start-placeholder="协议开始日期"
                end-placeholder="协议结束日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div
        class="operationBox tableSearch"
        style="margin-left:30px; margin-bottom:20px;float:left "
      >
        <el-button
          v-if="type=='2'&&(agreementStatus=='1'||agreementStatus=='2'||agreementStatus=='3')"
          v-show="iseditf"
          type="primary"
          @click="deletAll_goods()"
          size="mini"
        >删除</el-button>
      </div>
      <div
        class="operationBox tableSearch"
        style="margin-left:30px; margin-bottom:20px;float:right;margin-right:100px;"
      >
        <el-button
          type="primary"
          @click="establish()"
          v-show="isedit||type=='1'"
          v-if="(type=='2'&&(agreementStatus=='1'||agreementStatus=='2'||agreementStatus=='3'))||type=='1'"
          size="mini"
        >选择商品</el-button>
        <!-- 2019/5/24添加修改功能 -->
        <el-button
          type="primary"
          v-show="iseditf&&type=='2'"
          v-if="setRole('修改价格协议')&&type=='2'&&(agreementStatus=='1'||agreementStatus=='2'||agreementStatus=='3')"
          @click="handleEdit()"
          size="mini"
        >修改</el-button>
      </div>
      <!-- 搜索框 -->
      <div class="datastyle">
        <!-- 表格 -->
        <div class="tableMain">
         <h3 class="table-title" v-if="whetherEdit=='1'" style="margin-top:30px">协议原有商品列表</h3>
          <el-table
            :data="tableData"
            stripe
            style="width: 100%"
            @selection-change="changeFun_good_table"
          >
            <el-table-column v-if="type=='2'" type="selection" width="55" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="55"></el-table-column>
            <el-table-column prop="goodsName" label="商品名称" align="center">
              <template slot-scope="scope">
                <span v-show="scope.row.show==false">{{scope.row.goodsName}}</span>
                <el-input
                  v-show="scope.row.show==true"
                  v-model="scope.row.goodsName"
                  size="mini"
                  disabled
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="parameter" label="规格型号" align="center">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.parameter" :key="index">
                  <span v-if="item!=null">{{item.paramName}} :</span>
                  <span v-if="item!=null">{{item.paramValue}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="采供单位" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.unitName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsPrice" label="单价" align="center">
              <template slot-scope="scope">
                <sd-input :val.sync="scope.row.goodsPrice" v-show="scope.row.show==true"></sd-input>
                <span v-show="scope.row.show==false">{{scope.row.goodsPrice}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isFreight" label="含运费" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isFreight"
                  v-show="scope.row.show==true"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                  @change="Checkbox"
                ></el-switch>
                <span v-show="scope.row.show==false&&scope.row.isFreight=='1'">含运费</span>
                <span v-show="scope.row.show==false&&scope.row.isFreight=='0'">不含运费</span>
              </template>
            </el-table-column>
            <el-table-column prop="freight" label="运费" align="center">
              <template slot-scope="scope">
                <sd-input
                  :val.sync="scope.row.freight"
                  v-show="scope.row.show==true&&scope.row.isFreight=='0'"
                ></sd-input>
                <span v-show="scope.row.show==false&&scope.row.isFreight=='0'">{{scope.row.freight}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  v-show="scope.row.show==true&&scope.row.isShowEdit==true"
                  @click="handleCancel(scope.$index)"
                  size="mini"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pageblock">
          <el-button
            :disabled="isDisabled"
            size="small"
            type="primary"
            class="topage"
            @click="toPage"
          >确定</el-button>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,10,20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
          ></el-pagination>
        </div>
      </div>
      <!-- 追加的商品 -->
      <div class="datastyle" v-if="whetherEdit=='1'">
        <h3 class="table-title" style="margin-left:25px">协议追加商品列表</h3>
        <el-table :data="selection_goodnew">
          <el-table-column type="index" label="序号" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseUnit" label="采供单位" align="center"></el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center">
            <template slot-scope="scope">
              <sd-input :val.sync="scope.row.goodsPrice"></sd-input>
            </template>
          </el-table-column>
          <el-table-column prop="isFreight" label="含运费" align="center">
            <template slot-scope="scope">
              <el-switch
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
                v-model="scope.row.isFreight"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="freight" align="center" label="运费">
            <template slot-scope="scope">
              <sd-input :val.sync="scope.row.freight" v-show="scope.row.isFreight == '0'"></sd-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                v-show="scope.row.isShowEdit==true"
                @click="_handleDelete(scope.$index)"
                type="text"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="float:right;margin-right:100px;margin-top:10px;" v-if="addedit">
        <el-button type="primary" @click="goBacks()" size="mini">返回</el-button>
      </div>
      <div style="float:right;margin-right:100px;margin-top:10px;" v-if="addedits">
        <el-button type="primary" @click="goBack()" size="mini">取消</el-button>
        <el-button
          type="primary"
          v-show="isedit||type=='1'"
          v-if="type=='1'||(type=='2'&&(agreementStatus=='1'||agreementStatus=='2'||agreementStatus=='3'))"
          @click="submitForm('ruleForm')"
          size="mini"
        >确认</el-button>
      </div>
    </div>
    <!-- 商品选择弹出框 -->
    <el-dialog
      title="商品选择"
      class="addshopname"
      :visible.sync="dialogTableVisible_good"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
      width="60%"
    >
      <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
      <div class="tableSearch tableSearchs">
        <i class="el-input__icon el-icon-search" @click="searchSelect"></i>
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label label-width="15px">
            <el-input
              class="input"
              v-model="selectdata.keyword"
              size="small"
              style="width:210px"
              placeholder="输入商品名称/货号/条码搜索"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="goodArray"
        stripe
        border
        ref="multipleTablegood"
        tooltip-effect="dark"
        :row-key="getRowKeys"
        highlight-current-row
        @selection-change="changeFun_good"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.parameter" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null">{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageblock">
        <el-button size="mini" type="primary" class="Determine topage" @click="goods">确定</el-button>
        <el-pagination
          @size-change="handleSizeChange_good"
          @current-change="handleCurrentChange_good"
          :current-page="currentpage_good"
          :page-sizes="[5,10,20]"
          :page-size="pageSize_good"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total_good"
        ></el-pagination>
      </div>
      <div class="operationBox tableSearch">
        <el-button
          style="float:right;margin-left:40px;margin-right:40px;"
          size="mini"
          type="primary"
          @click="save_good"
        >确认</el-button>
        <el-button style="float:right" size="mini" @click=" dialogTableVisible_good = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import sdInput from "@/components/SdInput";
import state from "@/util/state";
import util from "@/util";
import {
  saveOrderPriceAgreement,
  findGoodsShopPage,
  getOrderPriceAgreementDetail,
  updateOrderPriceAgreement,
  deleteAgreementGoods
} from "@/api";
export default {
  components: { sdInput },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      userName: state => state.userName,
      companyName: state => state.companyName,
      power: state => state.power,
      userId: state => state.userId
    })
  },
  data() {
    return {
      getRowKeys(row) {
        return row.id; // 获取row的key值
      },
      ruleForm: {
        supplierName: "", //客户名称
        saleName: "", //协议名称
        agreementTime: [] //协议时间
      },
      rules: {
        saleName: [
          {
            required: true,
            message: "请填写销售价格协议名称",
            trigger: "blur"
          }
        ],
        agreementTime: [
          { required: true, message: "请选择协议起止时间", trigger: "blur" }
        ]
      },
      selectdata: {
        keyword: "" //商品输入关键字
      },
      isDisabled: "", //分页确定按钮
      shopId: "", //协议id
      tableData: [], //选过的商品数组
      dialogTableVisible_good: false, //商品弹窗
      selection_good: [],
      goodArray: [], //商品弹窗数组
      pageSize_good: 10, //商品分页
      currentpage_good: 1,
      total_good: 0,
      totalItems: 0, //表格分页
      currentPage: 1,
      pageSize: 10,
      type: "", //查看还是修改
      agreementStatus: "", //协议状态
      selection_good_table: [], //删除选择的值
      tableDataold: [], //修改前数组
      customerId: "", //客户id
      customerName: "", //客户名称
      isedit: false,
      iseditf: true,
      disableds: false, //协议时间
      addedit: false, //返回按钮显示隐藏
      addedits: false, //取消和确认按钮显示隐藏
      disabledName: true,
      whetherEdit: "0", //是否修改
      newData: [],
      selection_goodnew: []
    };
  },
  created() {
    this.type = util.getQuery().type;
    this.customerId = util.getQuery().customerId;
    this.customerName = util.getQuery().name;
    this.agreementStatus = util.getQuery().agreementStatus;
    this.shopId = util.getQuery().id; //协议id
    if (util.getQuery().type == "1") {
      this.ruleForm.supplierName = this.customerName;
      this.addedits = true;
      this.addedit = false;
      this.disabledName = false;
    } else {
      this.Procurement(this.pageSize, 1);
      this.disableds = true;
      this.addedits = false;
      this.addedit = true;
      this.disabledName = true;
    }
  },
  mounted() {},
  methods: {
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    ///查看详情数据
    Procurement(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        customerId: this.customerId,
        pageNum: pageNum,
        agreementId: this.shopId
      };
      getOrderPriceAgreementDetail(data).then(res => {
        this.ruleForm.supplierName = res.data.customerName;
        this.ruleForm.saleName = res.data.agreementName;
        this.ruleForm.agreementTime.push(util.foryear(res.data.startDate));
        this.ruleForm.agreementTime.push(util.foryear(res.data.endDate));
        this.totalItems = res.data.pageTotal;
        if (res.data.goodsList != undefined) {
          for (let i = 0; i < res.data.goodsList.length; i++) {
            res.data.goodsList[i].show = false;
            res.data.goodsList[i].isShowEdit = false;
            res.data.goodsList[i].isFreight = JSON.stringify(
              res.data.goodsList[i].isFreight
            );
            res.data.goodsList[i].parameter = res.data.goodsList[i].goodsSpec;
          }
          this.tableDataold = JSON.parse(JSON.stringify(res.data.goodsList));
          this.tableData = res.data.goodsList;
        }
        if (res.data.goodsList == undefined) {
          this.tableData = [];
        }
        if (this.whetherEdit == "1") {
          this.tableData.forEach(i => {
            i.show = true;
          });
        }
      });
    },
    // 删除连接接口
    deletAll_goods() {
      if (this.selection_good_table.length > 0) {
        this.$confirm("确定要删除吗?", "提示", {
          center: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false,
          closeOnPressEscape: false
        })
          .then(() => {
            let data = {
              goodsList: JSON.stringify(this.selection_good_table)
            };
            deleteAgreementGoods(data).then(res => {
              if (res.code == "200") {
                this.ruleForm.agreementTime = [];
                this.Procurement(this.pageSize, 1);
                this.$message({
                  type: "success",
                  message: res.msg
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          type: "error",
          message: "请选择要删除的商品"
        });
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    //---------新增保存
    handleSave() {
      let a = true;
      let b = true;
      this.tableData.forEach(i => {
        if (
          i.isFreight == "0" &&
          (i.freight == "0" || i.freight == undefined)
        ) {
          a = false;
          return;
        }
      });
      this.selection_goodnew.forEach(x => {
        if (
          x.isFreight == "0" &&
          (x.freight == "0" || x.freight == undefined)
        ) {
          b = false;
          return;
        }
      });
      if (this.type == "1") {
        let Datas = {
          supplierId: this.merchantId,
          agreementId: "", //协议id
          supplierName: this.companyName,
          customerId: this.customerId,
          customerName: this.customerName,
          creater: this.merchantId,
          agreementType: "", //协议类型
          startDate: this.ruleForm.agreementTime[0],
          endDate: this.ruleForm.agreementTime[1],
          agreementName: this.ruleForm.saleName,
          list: JSON.stringify(this.tableData)
        };
        if (a == false) {
          this.$message({
            type: "error",
            message: "不含运费时运费请输入大于0的数"
          });
        } else {
          saveOrderPriceAgreement(Datas).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg
              });
              history.back();
            }
          });
        }
      } else {
        let tableDataNew = [];
        this.tableDataold.forEach(item => {
          this.tableData.forEach(ele => {
            if (ele.isFreight == "1") {
              ele.freight = "0";
            }
            if (
              item.id === ele.id &&
              (item.isFreight != ele.isFreight ||
                item.freight != ele.freight ||
                item.goodsPrice != ele.goodsPrice)
            ) {
              tableDataNew.push(ele);
            }
          });
        });
        this.selection_goodnew.forEach(x => {
          if (!x.id) {
            tableDataNew.push(x);
          }
        });
        tableDataNew.forEach(i => {
          if (i.isFreight == "1") {
            i.freight = "0";
          }
        });
        let data = {
          orderPriceAgreement: {
            id: this.shopId,
            startDate: this.ruleForm.agreementTime[0],
            endDate: this.ruleForm.agreementTime[1]
          },
          goodsList: JSON.stringify(tableDataNew)
        };
        if (a == false || b == false) {
          this.$message({
            type: "error",
            message: "不含运费时运费请输入大于0的数"
          });
        } else {
          updateOrderPriceAgreement(data).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg
              });
              history.back();
              // this.tableData.forEach(item => {
              //   item.show = false;
              // });
              // this.isedit = false;
              // this.iseditf = true;
              // this.disableds = true;
              // this.addedits = false;
              // this.addedit = true;
              // this.ruleForm.agreementTime = [];
              // this.Procurement(this.pageSize, 1);
            }
          });
        }
      }
    },
    // 点击修改
    handleEdit() {
      this.tableData.forEach(item => {
        item.show = true;
      });
      this.isedit = true;
      this.iseditf = false;
      this.disableds = false;
      this.addedits = true;
      this.addedit = false;
      this.whetherEdit = "1";
    },
    // 返回
    goBacks() {
      history.back();
    },
    goBack() {
      // if (this.type == "1") {
      history.back();
      // } else {
      //   this.tableData.forEach(item => {
      //     item.show = false;
      //   });
      //   this.isedit = false;
      //   this.iseditf = true;
      //   this.disableds = true;
      //   this.addedits = false;
      //   this.addedit = true;
      //   this.ruleForm.agreementTime = [];
      //   this.Procurement(this.pageSize, 1);
      // }
    },
    changeFun_good_table(val) {
      if (val) {
        this.selection_good_table = val;
      } else {
        this.selection_good_table = [];
      }
    },
    //选择商品按钮
    establish() {
      if (this.ruleForm.agreementTime.length == 0) {
        this.$message({
          type: "error",
          message: "请选择协议起止时间"
        });
      } else {
        this.getGoods(this.pageSize_good, this.currentpage_good);
        this.dialogTableVisible_good = true;
      }
    },
    // 搜索商品按钮
    searchSelect() {
      this.getGoods(this.pageSize_good, 1);
    },
    // 商品弹窗内容
    getGoods(pageSize, pageNum) {
      let data = {
        searchInfo: this.selectdata.keyword,
        pageSize: pageSize,
        pageNo: pageNum,
        customerId: this.customerId,
        supplierId: this.merchantId,
        startDate: this.ruleForm.agreementTime[0],
        endDate: this.ruleForm.agreementTime[1],
        shopId: this.merchantId
      };
      findGoodsShopPage(data).then(res => {
        if (res.code == "200") {
          this.goodArray = res.data.list;
          this.total_good = res.data.total;
        }
      });
    },
    // 选择的商品
    save_good() {
      if (this.selection_good.length == 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } else {
        var self = this;
        this.selection_good = this.selection_good.map(item => {
          //遍历每次创建商品
          return {
            customerName: self.ruleForm.supplierName,
            status: 0,
            goodsName: item.name,
            goodsId: item.id,
            parameter: item.parameter,
            goodsSpec: item.parameter,
            goodsUnit: item.goodsPackParameterId,
            goodsPackParameterId: item.goodsPackParameterId,
            unitName: item.purchaseUnit,
            goodsCode: item.goodsCode,
            barCode: item.barCode,
            goodsPrice: item.goodsPrice,
            isFreight: "0",
            primaryClassify: item.primaryClassify,
            show: true,
            isShowEdit: true
          };
        });

        if (this.type == "1") {
          this.newData = [];
          this.tableData = this.tableData.concat(
            JSON.parse(JSON.stringify(this.selection_good))
          );
          this.tableData.forEach(cur => {
            if (!this.newData.some(i => i.goodsId === cur.goodsId)) {
              this.newData.push(cur);
            }
          });
          this.tableData = this.newData;
        } else {
          let selectiongoodnew = [];
          for (let i = 0; i < this.selection_good.length; i++) {
            if (
              !this.tableData.some(
                item => item.goodsId == this.selection_good[i].goodsId
              )
            ) {
              selectiongoodnew.push(this.selection_good[i]);
            }
          }
          this.selection_goodnew = this.selection_goodnew.concat(
            JSON.parse(JSON.stringify(selectiongoodnew))
          );
          let news = [];
          this.selection_goodnew.forEach(cur => {
            if (!news.some(i => i.goodsId == cur.goodsId)) {
              news.push(cur);
            }
          });
          this.selection_goodnew = news;
          console.log(this.selection_goodnew)
        }

        this.$refs.multipleTablegood.clearSelection();
        this.dialogTableVisible_good = false;
      }
    },
    // 选择商品
    changeFun_good(val) {
      if (val) {
        this.selection_good = val;
      } else {
        this.selection_good = [];
      }
    },
    //前端控制删除单调商品
    handleCancel(index) {
      this.tableData.splice(index, 1);
    },
    _handleDelete(index) {
      this.selection_goodnew.splice(index, 1);
    },
    Checkbox(vel) {},
    //表格分页
    toPage() {
      this.ruleForm.agreementTime = [];
      this.Procurement(this.pageSize, this.currentPage);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.isDisabled = false;
      this.ruleForm.agreementTime = [];
      this.Procurement(val, this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.ruleForm.agreementTime = [];
      this.Procurement(this.pageSize, val);
    },
    // 商品分页
    goods() {
      this.getGoods(this.pageSize_good, this.currentpage_good);
    },
    handleSizeChange_good(val) {
      this.pageSize_good = val;
      this.getGoods(val, this.currentpage_good);
    },
    handleCurrentChange_good(val) {
      this.currentpage_good = val;
      this.getGoods(this.pageSize_good, val);
    }
  }
};
</script>
<style scoped>
.datastyles {
  position: relative;
  width: 378px;
  height: 40px;
}
.th-right {
  margin-left: 568px;
}
.tableSearchs {
  position: relative;
}
.tableSearchs .el-input__icon {
  position: absolute;
  top: 12px;
  left: 200px;
  z-index: 10;
  width: 25px;
  height: 35px;
}
.table-title {
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  font-weight: 500;
}
</style>
<style>
.datastyle .el-table .cell,
.el-table th div {
  overflow: visible;
}
.el-input__inner {
  padding: 0 20px;
}
.salePrice .editRule .el-input-group--prepend .el-input__inner,
.el-input-group__append {
  border: solid 1px #579ff8;
  background-color: #579ff8;
  color: #ffffff;
}
.salePrice {
  text-align: left;
}
</style>


